package com.bootdo.wechat.controller;

import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.UserDO;
import com.bootdo.wechat.config.WxHandlerInitialize;
import com.bootdo.wechat.domain.MpConfigDO;
import com.bootdo.wechat.service.MpConfigService;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author songj
 * @version ${VERSION}
 * @Title: bootdo-wechat
 * @Package com.bootdo.wechat.controller
 * @Description: ${TOTO} (用一句话描述该文件做什么)
 * @date 2018/7/31  9:06
 */
public class MpBaseController {

    @Autowired
    private MpConfigService mpConfigService;

    /**
     * 根据特定的id获取公众号信息 构建wxservice
     * @param id
     * @return
     */
    public WxMpService getWxService(String id){
        WxMpService wxMpService = new WxMpServiceImpl();
        WxMpInMemoryConfigStorage configStorage  =new WxMpInMemoryConfigStorage();
        MpConfigDO mpConfigDO = mpConfigService.selectById(id);
        configStorage.setAppId(mpConfigDO.getMpAppId());
        configStorage.setSecret(mpConfigDO.getMpAppSecret());
        configStorage.setToken(mpConfigDO.getMpToken());
        configStorage.setAesKey(mpConfigDO.getMpAesKey());
        wxMpService.setWxMpConfigStorage(configStorage);
        return wxMpService;
    }


    /**
     * 构建消息路由
     * @param id
     * @return
     */
    public WxMpMessageRouter getRouter(String id){
        WxHandlerInitialize wxHandlerInitialize = new WxHandlerInitialize();
        WxMpMessageRouter router = wxHandlerInitialize.router(getWxService(id));
        return router;
    }

    /**
     * 获取当前登陆用户
     * @return
     */
    public UserDO getUser() {
        return ShiroUtils.getUser();
    }

    public long getUserId(){return ShiroUtils.getUserId();}
}
